import os
from django.db import models
import string
import random
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from django.utils import timezone

# 自定义存储类，将文件保存到 file_storage 目录
class FileStorage(FileSystemStorage):
    def __init__(self):
        super().__init__(location=settings.FILE_ROOT, base_url=None)

class ShortURL(models.Model):
    original_url = models.URLField(max_length=2000)
    short_code = models.CharField(max_length=10, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    @classmethod
    def create_short_url(cls, original_url):
        # 生成6位随机短码
        chars = string.ascii_letters + string.digits
        while True:
            short_code = ''.join(random.choice(chars) for _ in range(6))
            if not cls.objects.filter(short_code=short_code).exists():
                break
        return cls.objects.create(
            original_url=original_url,
            short_code=short_code
        )

    def get_short_url(self, request):
        return request.build_absolute_uri(f'/s/{self.short_code}/')

class File(models.Model):
    """文件模型，用于 admin 后台管理"""

    def get_upload_path(instance, filename):
        # 动态生成上传路径
        if hasattr(instance, '_upload_dir') and instance._upload_dir:
            return os.path.join(instance._upload_dir, filename)
        return filename

    file = models.FileField(
        upload_to=get_upload_path,  # 使用动态路径
        storage=FileStorage(),
        verbose_name='文件',
        blank=True,
        null=True,
    )
    name = models.CharField(max_length=255, verbose_name='文件名')
    upload_time = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    file_size = models.BigIntegerField(default=0, verbose_name='文件大小(字节)')
    upload_dir = models.CharField(max_length=50, verbose_name='上传目录', blank=True, null=True, help_text='相对于file_storage的目录路径')

    class Meta:
        verbose_name = '文件上传'
        verbose_name_plural = '文件上传'
        ordering = ['-upload_time']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.file and not self.name:
            self.name = os.path.basename(self.file.name)
        if self.file:
            self.file_size = self.file.size
        # 设置上传目录
        if self.upload_dir:
            self._upload_dir = self.upload_dir
        super().save(*args, **kwargs)

class FileIndex(models.Model):
    """文件索引表，用于加速搜索"""
    path = models.CharField(max_length=512, unique=True, verbose_name='相对路径')
    name = models.CharField(max_length=255, verbose_name='文件名')
    size = models.BigIntegerField(verbose_name='文件大小(字节)')
    mtime = models.DateTimeField(verbose_name='最后修改时间')
    is_dir = models.BooleanField(default=False, verbose_name='是否目录')

    class Meta:
        verbose_name = '文件索引'
        verbose_name_plural = '文件索引'
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['path']),
        ]
        ordering = ['-mtime']

    def __str__(self):
        return self.path
